package top.lywivan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Constants;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import top.lywivan.reggie.service.EmployeeService;
import com.itheima.reggie.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/employee")
@Slf4j
//@Api(tags = "员工的控制层相关接口")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    /**
     * 实现后台登陆功能
     * @param session 用于存储登陆用户的id
     * @param employee 接收前端参数
     * @return
     */
    @PostMapping("/login")
    /*@ApiOperation("员工登陆接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "employee",value = "员工用户名和密码",required = true),
    })*/
    public R login(HttpSession session, @RequestBody Employee employee){
        String username = employee.getUsername();
        String password = employee.getPassword();
        //使用MD5算法计算
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        Employee one = employeeService.getOne(Wrappers.<Employee>lambdaQuery().eq(Employee::getUsername, username));
        if (one==null){
            return R.error("用户名不存在");
        }
        if (!one.getPassword().equals(password)){
            return R.error("密码不正确");
        }
        if (one.getStatus()==0){
            return R.error("该账户已被禁用");
        }
        //将登陆的用户id存入session
        session.setAttribute(Constants.EMPLOYEE_ID_SESSION_KEY,one.getId());
        //削减部分数据后返回给前端
        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(one,employeeVo);

        log.info("登陆成功");
        return R.success(employeeVo);
    }

    /**
     * 实现登出功能
     * @param session 从session中移除用户信息
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();

        log.info("登出成功");
        return R.success("登出成功");
    }

    /**
     * 实现添加员工功能
     * @param session 获取添加人的id
     * @param employee 前端传递的参数
     * @return
     */
    @PostMapping
    public R save(HttpSession session,@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex(Constants.EMPLOYEE_DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
        employee.setStatus(1);
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long) session.getAttribute("employee");
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);*/
        employeeService.save(employee);
        return R.success("添加员工成功");
    }

    /**
     * 分页查询员工列表
     * @param page 当前页码
     * @param pageSize 每页显示条数
     * @param name 查询条件
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam(required = false,defaultValue = "1") Long page,@RequestParam(required = false,defaultValue = "10") Long pageSize,String name){
        LambdaQueryWrapper<Employee> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(name!=null,Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        Page<Employee> beforePage = new Page<>(page, pageSize);
        Page<Employee> result = employeeService.page(beforePage, queryWrapper);
        return R.success(result);
    }

    /**
     * 禁用启用员工账户
     * 由于js的long类型的精度损失，需要我们重新书写json的类型转换器
     * @param employee 包括修改的内容
     * @param session 获取修改人id
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
        /*Long employeeId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(employeeId);
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询员工信息，用于修改时回显数据
     * @param id 要修改的员工id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }

    /**
     * 根据用户名查询用户，用于失焦判断用户名是否可用（锦上添花）
     * @param username 传入的用户名
     * @return
     */
    /*@GetMapping("/getByName/{username}")
    public R getByUsername(@PathVariable("username")String username){
        Employee employee = employeeService.getOne(Wrappers.<Employee>lambdaQuery().eq(Employee::getUsername, username));
        if (employee!=null){
            return R.error("用户名已存在!!!");
        }else {
            return R.success("可以注册");
        }
    }*/
}
